<template>
  <div class="login_container">
    <div class="login_box">
      <div class="login">
        <img src="./../assets/logo.png" alt="">
      </div>
      <el-form :model="userForm" :rules="userFormRules" ref="userFormRef">
        <!--        用户名-->
        <el-form-item prop="username">
          <el-input prefix-icon="iconfont icon-user" v-model="userForm.username"/>
        </el-form-item>
        <!--        密码区-->
        <el-form-item prop="password">
          <el-input prefix-icon="iconfont icon-3702mima" v-model="userForm.password"/>
        </el-form-item>
        <el-form-item class="buttons">
          <el-button type="primary" @click="login">登录</el-button>
          <el-button type="info" @click="userFormReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data () {
    return {
      // 用户登录表单
      userForm: {
        username: 'admin',
        password: '123456'
      },
      userFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
  },
  methods: {
    // 重置表单数据
    userFormReset () {
      this.$refs.userFormRef.resetFields()
    },
    // 表单登录验证
    login () {
      this.$refs.userFormRef.validate(async valid => {
        // console.log(valid)
        if (!valid) return this.$message.error('您输入的信息有误')
        const { data: res } = await this.$http.post(`login`, this.userForm)
        if (res.meta.status !== 200) return this.$message.error('登录失败')
        this.$message.success(res.meta.msg)
        // 登录成功之后将token保存在客户端
        window.sessionStorage.setItem('token', res.data.token)
        // 通过编程式导航跳转到home页面
        this.$router.push('/home')
      })
    }
  }
}
</script>

<style scoped lang="less">
  .login_container {
    background-color: #2b4b6b;
    height: 100%;

    .login_box {
      width: 450px;
      height: 250px;
      background-color: #fff;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      padding: 0 15px;

      .login {
        width: 80px;
        height: 80px;
        position: absolute;
        /*top: -50%;*/
        left: 50%;
        transform: translate(-50%, -50%);
        background-color: #ccc;
        border-radius: 50%;
        padding: 5px;

        img {
          width: 100%;
          height: 100%;
          border-radius: 50%;
        }
      }

      .el-form {
        margin-top: 70px;
      }
      .buttons{
        display: flex;
        justify-content: flex-end;
      }
    }
  }
</style>
